import { exec } from 'child_process';
import fs from 'fs';
import { marked } from 'marked';
import { createRequire } from 'module';
import path, { dirname } from 'path';
import prettier from 'prettier';
import { fileURLToPath } from 'url';

marked.use({
  async: true,
  pedantic: false,
  gfm: true,
});

function copy(params) {
  exec('pbcopy').stdin.end(params);
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);
const cwd = process.cwd();
const prettierrc = JSON.parse(
  fs.readFileSync(path.resolve(cwd, '.prettierrc'), 'utf8'),
);
const toPath = path.resolve(cwd, 'src/mobile/views');

let p = 'components/mobile/_basic';
let a = fs.readdirSync(path.resolve(cwd, p)).filter(v => {
  return fs.statSync(path.resolve(cwd, p, v)).isDirectory();
});
// a = [a[0]];
for (let i = 0; i < a.length; i++) {
  const e = a[i];
  let fpd = path.resolve(cwd, p, e);
  let readme = path.resolve(fpd, 'README.zh-CN.md');
  let demo = path.resolve(fpd, 'demo');
  if (fs.existsSync(demo)) {
    let tpd = path.resolve(toPath, e);
    fs.rmSync(tpd, { recursive: true, force: true });
    fs.mkdirSync(tpd);
    let a_ = fs.readdirSync(path.resolve(cwd, demo));
    for (let j = 0; j < a_.length; j++) {
      const e_ = a_[j];
      let demoItem = path.resolve(demo, e_);
      // fs.cpSync(demo, tpd, { recursive: true, force: true })

      let r = fs.readFileSync(demoItem, 'utf8');
      r = r.replace(
        /import \{(.+)\} from '\.\.\/\.\.\/\.\.\/docs\/site';/g,
        `import { $1 } from 'tm/_utils';`,
      );
      r = r.replaceAll(`'../../utils`, `'tm/_basic/utils`);
      r = r.replaceAll(`'../../composables`, `'tm/_basic/composables`);
      r = r.replaceAll(`'../../area`, `'tm/_basic/area`);
      r = r.replaceAll(`'../../field`, `'tm/_basic/field`);
      r = r.replaceAll(`'../../picker`, `'tm/_basic/picker`);
      r = r.replaceAll(`'../../lazyload`, `'tm/_basic/lazyload`);
      r = r.replaceAll(`'../../locale`, `'tm/basic/locale`);
      r = r.replaceAll(`'../../`, `'tm/basic/`);
      r = r.replaceAll(`'..'`, `'tm/basic/${e}'`);
      r = r.replaceAll(`demo-block`, `tm-demo-block`);
      if (e_.endsWith('.vue')) {
        r = await prettier.format(r, { ...prettierrc, parser: 'vue' });
      }
      fs.writeFileSync(path.resolve(tpd, e_), r, { encoding: 'utf-8' });
    }
  }

  if (fs.existsSync(readme)) {
    let r = fs.readFileSync(readme, 'utf8');
    const tokens = marked.lexer(r);
    let t = tokens[0].text.split(' ');
    // r = await prettier.format(r, { ...prettierrc, parser: 'babel-ts' });
    // fs.writeFileSync(readme, r, { encoding: 'utf-8' });
  }
}

// fs.writeFileSync(
//   path.resolve(cwd, 'components/mobile/style/index.scss'),
//   style,
//   { encoding: 'utf-8' },
// );
